package com.study.spaoplog.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @author MI
 * @version 1.0
 * @date 2021/6/20 20:40
 */
@Slf4j
@Service
public class QpsService {
    @Autowired
    private RedisTemplate redisTemplate;

    public Map<String, Object> startLoutong(Map<String, Object> paramMap) {
        String redisKey = "qpsList";
        Integer times = 100;
        if (paramMap.containsKey("times")) {
            times = Integer.valueOf(paramMap.get("times").toString());
        }
        Long size = redisTemplate.opsForList().size(redisKey);
        if (size >= times) {
            throw new RuntimeException("qps refuse request");
        }
        Long aLong = redisTemplate.opsForList().rightPush(redisKey, paramMap);
        if (aLong > times) {
            //为了防止并发场景。这里添加完成之后也要验证。  即使这样本段代码在高并发也有问题。此处演示作用
            redisTemplate.opsForList().trim(redisKey, 0, times - 1);
            throw new RuntimeException("qps refuse request");
        }
        Map<String, Object> map = new HashMap<>();
        map.put("success", "success");
        return map;
    }

}
